package com.linkage.jz.bankruptcy.activity.Project;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.GetPwdOneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailAuthBaseInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.fragment.Project.SelZQUserConfirmListFrgment;
import com.linkage.jz.bankruptcy.fragment.Project.ZQUserConfirmListFrgment;
import com.linkage.jz.bankruptcy.fragment.Project.ZQUserToBeConfirmListFrgment;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CreateZQUserDialog;
import com.linkage.jz.bankruptcy.widget.CreateZQUserNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PopupMenuPublicPro;
import com.linkage.jz.bankruptcy.widget.PopupMenuZQ;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.message.MultiMessageHistoryActivity;
import com.linkage.seapeak.activity.message.MultiSelectActivity;
import com.linkage.seapeak.activity.message.ZQScreenUserActivity;
import com.linkage.seapeak.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public class SelZQUserListActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    private TextView topBtn01, topBtn02;
    private LinearLayout topBtnContainer;
    private ViewPager mViewPager;
    private TabPagerAdapter mPagerAdapter;
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private ShapeLoadingDialog shapeLoadingDialog;
    private CreateZQUserDialog createUserDialog;
    private CreateZQUserNoticeDialog createZQUserNoticeDialog;
//    private static MyProInfo mInfo;
    private PopupMenuZQ popupMenu;
    private ZQUserDetailAuthBaseInfo mAuthBaseInfo;
    private int changeType = -1;
    private static String isOpen;

    //    TextView top_title;
    View top_back;
    ImageView top_mune;

    private static String mProId;
    public static void start(Context context, String proid,String open) {
        mProId = proid;
        isOpen = open;
        Intent intent = new Intent(context, SelZQUserListActivity.class);
        context.startActivity(intent);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarMode(false);
        setContentView(R.layout.activity_pro_zquserlist_sel);
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        ActionBar bar = this.getActionBar();
        if (bar != null) {
            bar.hide();
        }
        initview();
        init();
//        getData();
//        EventBus.getDefault().register(this);
        popupMenu = new PopupMenuZQ(this);
    }

    int pageType = 1;

    public void showAddZQUser( ) {

        pageType = 1;
        createUserDialog = new CreateZQUserDialog(SelZQUserListActivity.this, onClickListener);
        createUserDialog.show();

    }

    public void menuShow(Boolean flag) {

//        if(flag)
//        {
//            top_mune.setVisibility(View.VISIBLE);
//        }else{
//            top_mune.setVisibility(View.INVISIBLE);
//        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.ADDZQUSRFLOW)) {
            pageType = 1;
            createUserDialog = new CreateZQUserDialog(SelZQUserListActivity.this, onClickListener);
            createUserDialog.show();
        }

        if(TextUtils.equals(event.getType(), RefreshEvent.ZQNOSHOWMENU)) {

        }

        if(TextUtils.equals(event.getType(), RefreshEvent.ZQSHOWMENU)) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);
//        if (mInfo == null) {
//            return;
//        }
//        if("".equalsIgnoreCase(mInfo.getmTeamId()))
//        {
            top_mune.setVisibility(View.INVISIBLE);
//        }


        top_mune.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                PopupMenuPublicPro popupMenu;
                ArrayList<String> ary = new ArrayList<String>();
                popupMenu = new PopupMenuPublicPro(SelZQUserListActivity.this);
                if (mAuthBaseInfo != null) {


                    if (mAuthBaseInfo.isAddCreditor()) {
                        ary.add("添加债权人");
                    }
//                    if (mInfo.getAuth().isEditCreditorBasicInfo() || mInfo.getAuth().isEditCreditorBasicInfo()) {
                        ary.add("债权人筛选");
//                    }
                    if (mAuthBaseInfo.isGroupSentMessage()) {
                        ary.add("群发消息");
                        ary.add("群发消息记录");
                    }

//                    if (ary.size() > 0) {

//                    } else {
//                        findViewById(R.id.menu_ddd).setVisibility(View.INVISIBLE);
//                    }

                }else {
                    ary.add("债权人筛选");
                }
                popupMenu.initData(ary);

                popupMenu.showLocation(R.id.top_mune);// 设置弹出菜单弹出的位置


                // 设置回调监听，获取点击事件
//                popupMenu.setOnItemClickListener(new PopupMenuPublicPro.OnItemClickListener() {
//
//                    @Override
//                    public void onClick(PopupMenuPublicPro.MENUITEM item, String str) {
//                        if ("添加债权人".equalsIgnoreCase(str)) {
////                            convertOnlineStatus(2);
//                            pageType = 1;
//                            createUserDialog = new CreateZQUserDialog(SelZQUserListActivity.this, onClickListener);
//                            createUserDialog.show();
//                        } else if ("债权人筛选".equalsIgnoreCase(str)) {
////                            convertOnlineStatus(1);
//                            ZQScreenUserActivity.start(SelZQUserListActivity.this,mInfo.getId());
//                        } else if ("群发消息".equalsIgnoreCase(str)) {
////                            settingCommittee(2);
//                            MultiSelectActivity.start(SelZQUserListActivity.this, mInfo.getId());
//                        } else if ("群发消息记录".equalsIgnoreCase(str)) {
////                            settingCommittee(1);
//                            MultiMessageHistoryActivity.start(SelZQUserListActivity.this, mInfo.getId());
//                        }
//
//
////                    Toast.makeText(ZQUserDetailActivity.this,str,Toast.LENGTH_LONG).show();
//                    }
//                });
//            }
//                createUserDialog = new CreateUserDialog(ManagerListActivity.this,onClickListener);
//                createUserDialog.show();
//                popupMenu.showLocation(R.id.top_mune);// 设置弹出菜单弹出的位置
//                // 设置回调监听，获取点击事件
//                popupMenu.setOnItemClickListener(new PopupMenuZQ.OnItemClickListener() {
//
//                    @Override
//                    public void onClick(PopupMenuZQ.MENUITEM item, String str) {
//                        if (item == PopupMenuZQ.MENUITEM.ITEM1) {
//                            pageType = 1;
//                            createUserDialog = new CreateZQUserDialog(ZQUserListActivity.this, onClickListener);
//                            createUserDialog.show();
//                        } else if (item == PopupMenuZQ.MENUITEM.ITEM2) {
//                            //债权人筛选
////                            startActivityForResult(new Intent(ZQUserListActivity.this, ZQScreenUserActivity.class), 0x11);
//                            ZQScreenUserActivity.start(ZQUserListActivity.this,mInfo.getId());
//                        } else if (item == PopupMenuZQ.MENUITEM.ITEM3) {
//                            //群发消息
//                            MultiSelectActivity.start(ZQUserListActivity.this, mInfo.getId());
//                        } else if (item == PopupMenuZQ.MENUITEM.ITEM4) {
//                            //群发消息记录
//                            MultiMessageHistoryActivity.start(ZQUserListActivity.this, mInfo.getId());
//                        }
//                    }
//                });
//
            }
        }
        );
    }

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_zq_u:

                    if (pageType == 1) {
                        String name = createUserDialog.text_name_zq_u.getText().toString().trim();
                        String phone = createUserDialog.text_mobile_zq_u.getText().toString().trim();
                        if("".equalsIgnoreCase(name))
                        {
                            ToastUtil.showShort("请填写债权人姓名");
                            return;
                        }

//                        addZQUser(name, phone, "","");

                    }
                    if (pageType == 2) {
                        String name = createUserDialog.text_name_zq_u.getText().toString().trim();
                        String phone = createUserDialog.text_mobile_zq_u.getText().toString().trim();
//                        if("".equalsIgnoreCase(phone))
//                        {
//                            addZQUser(name, phone, "2","false");
//                        }else{
//                            addZQUser(name, phone, "","");
//                        }
                        createZQUserNoticeDialog.dismiss();
                    }
                    break;
                case R.id.btn_save_zq_u:




                    break;

            }
        }
    };


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //返回
                MainActivity.start(this);
                finish();
                break;
            case R.id.ll_phonelogin:
                PhoneLoginActivity.start(this);
                finish();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.getPwd:
                GetPwdOneActivity.start(this);
            case R.id.id_dcphGroup_topBtn01:
                changeFragmentFocus(0);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.id_dcphGroup_topBtn02:
                changeFragmentFocus(1);
                mViewPager.setCurrentItem(1);
                break;
            default:
                break;
        }
    }

    private void init() {
        top_back.setOnClickListener(this);

        SelZQUserConfirmListFrgment groupChildrenCollect = new SelZQUserConfirmListFrgment();
//        ZQUserToBeConfirmListFrgment groupChildrenHasBuy = new ZQUserToBeConfirmListFrgment();
        Bundle bundle = new Bundle();


        bundle.putString("proid", mProId);//这里的values就是我们要传的值
        bundle.putString("isOpen", isOpen);


        groupChildrenCollect.setArguments(bundle);

//        groupChildrenHasBuy.setArguments(bundle);

        fragments.add(groupChildrenCollect);
//        fragments.add(groupChildrenHasBuy);

        topBtn01 = (TextView) this.findViewById(R.id.id_dcphGroup_topBtn01);
//        topBtn02 = (TextView) this.findViewById(R.id.id_dcphGroup_topBtn02);
        topBtnContainer = (LinearLayout) this.findViewById(R.id.id_dcphGroup_topBtn_container);
        topBtn01.setOnClickListener(this);
//        topBtn02.setOnClickListener(this);
        mViewPager = (ViewPager) this.findViewById(R.id.id_dcphGroup_viewPager);
        mPagerAdapter = new TabPagerAdapter(this.getSupportFragmentManager(), fragments);

        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.invalidate();
        mPagerAdapter.notifyDataSetChanged();
    }

    /*
     * 自定义FragmentStatePagerAdapter适配器来显示滑动Fragment
     * */
    private class TabPagerAdapter extends FragmentStatePagerAdapter implements
            ViewPager.OnPageChangeListener {

        private ArrayList<Fragment> objects;

        public TabPagerAdapter(FragmentManager fm, ArrayList<Fragment> objects) {
            super(fm);
            this.objects = objects;
            mViewPager.setOnPageChangeListener(this);
        }

        @Override
        public Fragment getItem(int position) {
            return objects.get(position);
        }

        @Override
        public int getCount() {
            return objects.size();
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //滑动的监听事件
            changeFragmentFocus(position);
        }
    }


    private void changeFragmentFocus(int focus) {
        if (focus == 0) {
//            topBtn01.setBackgroundResource(R.drawable.about_b_corner_btn);
//            topBtn02.setBackgroundResource(R.drawable.about_g_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.black));
            topBtn02.setTextColor(getResources().getColor(R.color.text_secondary_color));
        } else if (focus == 1) {
//            topBtn01.setBackgroundResource(R.drawable.about_g_corner_btn);
//            topBtn02.setBackgroundResource(R.drawable.about_b_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.text_secondary_color));
            topBtn02.setTextColor(getResources().getColor(R.color.black));
        }
    }



    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

//        final  String title = law_searchtxt.getText().toString();

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("projectId",mProId)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("creditorName","")
                .add("process","0,1,2,3,4")
                .add("pageNo","1")
                .add("pageSize","10")
                .build();

        String url = Consts.WEBURL_CONFIRMEDLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                shapeLoadingDialog.dismiss();


                String str = response.body().string();

                try{


                    final JSONObject object = new JSONObject(str);
                    JSONObject data = object.getJSONObject("data");

                    mAuthBaseInfo= new Gson().fromJson(data.getJSONObject("auth").toString(), ZQUserDetailAuthBaseInfo.class);
//                    mInfo.setAuth(authBaseInfo);

                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }

}


